import os

import execjs
import requests
import re
def search():
    url = 'https://search.douban.com/movie/subject_search?search_text={}&start='.format('你好', 0)
    request_headers = {
        "Referer": "https://movie.douban.com/",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36 SocketLog(tabid=366&client_id=)"
    }
    response = requests.get(url, headers=request_headers)
    text = response.text

    result = re.findall('window.__DATA__ = "([\s\S]*?)"', text)
    if not result:
        return '未获取到豆瓣加密数据'
    r = result[0]
    path = os.path.join(os.getcwd(), 'js', 'main.js')
    with open(path, 'r',encoding='utf-8', errors="ignore") as f:
        decrypt_js = f.read()
    ctx = execjs.compile(decrypt_js)
    data = ctx.call('decrypt', r)
    payload = data.get('payload',[])
    items = []
    temp = []
    if payload:
        items = payload.get('items',[])
    if items:
        for i in items:
            var = {
            "movie_id": i.get('id'),
            "movie_name": i.get('title'),
            "score": i.get('rating')['value'],
            "star": i.get('rating')['star_count'],
            "image": i.get('cover_url')
            }
            temp.append(var)
    return temp
result = search()
print(result)